<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller;

use buwang\base\AdminBaseController;
use think\facade\Filesystem;
use app\manage\model\ConfigGroup;
use app\common\model\Miniapp;
class Group extends AdminBaseController
{
    /*protected $middleware = [
        'login' => ['except' => []]
    ];*/

    public function index()
    {
        $miniapp = Miniapp::select()->toArray();
        return view('',['miniapp' => $miniapp]);
    }


    /**
     * 配置分类列表
     *
     * @return \think\Response
     */
    public function getconfiglist()
    {
        //搜索条件
        $map = array();
        $sort = 'a.id desc';
        //页数
        $page = input('page/d');
        //条数
        $limit = input('limit/d');
//        //时间开始
//        $time_start    = input('beginTime/s');
//        //时间结束
//        $time_end    = input('endTime/s');
        //订单状态
        $id = input('id/d');
        $name = input('name/s');

        //手机号
        $config_name = input('config_name/s');
        $scopes = input('scopes/s');
        $dir = input('dir/s');

        if($dir){
            $map[] = ['a.dir', '=', $dir];
        }
        if ($scopes) {
            $map[] = ['a.scopes', '=', $scopes];
        }
        //订单状态
        if ($id != null) {
            $map[] = ['a.id', '=', $id];
        }


        if ($name) {
            $map[] = ['a.name', 'like', $name . '%'];
        }
        if ($config_name) {
            $map[] = ['a.config_name', 'like', $config_name . '%'];
        }


////        //时间区间
//        if($time_start!=null){
//            $time_start = strtotime($time_start);
//            $map[] = ['a.add_time','>=',$time_start];
//            if($time_end!=null){
//                $time_end = strtotime($time_end);
//                $map[] = ['a.add_time','<=',$time_end];
//            }
//        }elseif($time_end!=null){
//            $time_end = strtotime($time_end);
//            $map[] = ['a.add_time','<=',$time_end];
//            if($time_start!=null){
//                $time_start = strtotime($time_start);
//                $map[] = ['a.add_time','>=',$time_start];
//            }
//        }

        // $map[] = ['a.is_del','=', 0];

        //门店列表
        $list = ConfigGroup::alias('a')
            ->join('miniapp m','m.dir = a.dir','left')
            ->field(['a.*','m.title as miniapp_name'])
            ->where($map)
            ->page($page, $limit)
            ->order($sort)
            ->select();
        //echo Db::name('offline_order')->getLastSql();die;//打印最后一条
        //echo Db::table('contract')->getLastSql();die;//打印最后一条sql
        $count = ConfigGroup::alias('a')
            ->join('miniapp m','m.dir = a.dir','left')
            ->where($map)
            ->count();

        //总数
        //列表数据
        $data = array();
        $data['code'] = 0;
        $data['msg'] = '查询成功';
        $data['count'] = $count;
        $data['data'] = $list;
        return json($data);
    }

    public function add()
    {

        if ($this->request->isPost()) {
            $param = $this->request->param();
            // if(!$param['auth_name']) return $this->error('权限标识必填');
            $fields = array();
            $unique_array = array();
            foreach ($param['fields'] as $field) {
                //if((htmlspecialchars_decode($field)));
                $rs = json_decode(htmlspecialchars_decode($field), true);
                if ($rs) {
                    $unique_array[] = $rs['config_name'];
                    $fields[] = $rs;

                }
            }

            ///判断是否有重复字段
            if (count($unique_array) != count(array_unique($unique_array))) {
                return $this->error('添加的字段中存在同名字段，请检查您的字段，去除同名字段！');
            }
            $param['fields'] = str_replace("\\\\", "\\", json_encode($fields, JSON_UNESCAPED_UNICODE));//数组转json$fields;
            //var_dump($param);die;//数组转json);
            //判断是否存在唯一标识
            $count = ConfigGroup::where('config_name', $param['config_name'])->where('dir',$param['dir'])->count();
            if ($count) return $this->error('该字段已存在');
            $result = ConfigGroup::create($param);
            if ($result) {
                //xn_add_admin_log('添加权限节点');
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败');
            }
        }
        $miniapp = Miniapp::select()->toArray();
        return view('edit', ['entity' => null, 'fields' => [],'miniapp' => $miniapp]);
    }


    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();

            $fields = array();
            $unique_array = array();
            foreach ($param['fields'] as $field) {
                //if((htmlspecialchars_decode($field)));
                $rs = json_decode(htmlspecialchars_decode($field), true);
                if ($rs) {
                    //如果是富文本则解析富文本数据
                    $unique_array[] = $rs['config_name'];
                    $fields[] = $rs;

                }
            }

            ///判断是否有重复字段
            if (count($unique_array) != count(array_unique($unique_array))) {
                return $this->error('添加的字段中存在同名字段，请检查您的字段，去除同名字段！');
            }
            $param['fields'] = str_replace("\\\\", "\\", json_encode($fields, JSON_UNESCAPED_UNICODE));//数组转json$fields;
            //var_dump($param['fields']);die;
            //  var_dump($param['fields']);die;
            //判断是否存在唯一标识
            $count = ConfigGroup::where('config_name', $param['config_name'])->where('dir',$param['dir'])->where('id', '<>', $param['id'])->count();
            if ($count) return $this->error('该字段已存在');


            $result = ConfigGroup::update($param);
            if ($result) {
                //xn_add_admin_log('修改管理组名称');
                return $this->success('更新成功');
            } else {
                return $this->error('操作失败');
            }
        }
        $id = $this->request->get('id');
        $data = ConfigGroup::find($id);
        $fields = array();
        if ($data) {
            $fieldsdata = $data['fields'];
            if ($fieldsdata) {
                $fieldsdata = json_decode($fieldsdata, true);//json串传数组
                if ($fieldsdata) $fields = $fieldsdata;
                //var_dump($fields);die;
                foreach ($fields as &$field) {
                    if ($field) {
                        //var_dump($field);die;
                        $field['json'] = str_replace("\\\\", "\\", json_encode($field, JSON_UNESCAPED_UNICODE));
                        // var_dump($field['json']);die;

                        $field['type_name'] = ConfigGroup::getTypeName($field['type']);
                    }

                }

            }


        }

        $miniapp = Miniapp::select()->toArray();
        return view('', ['entity' => $data, 'fields' => $fields,'miniapp' => $miniapp]);
    }


    public function addconfig()
    {

        if ($this->request->isPost()) {
            $param = $this->request->param();
            unset($param['radio_value']);
            unset($param['checkbox_value']);
            unset($param['select_value']);
            if (in_array($param['config_name'], ['sort', 'status'])) return $this->error('字段[sort],[status]属于组合数据字段，请换个字段名');

            $param['id'] = uniqid();
//              $data = json_decode($param, true);//json串传数组
//              if(!$data)return $this->error('操作失败');
            return $this->success('操作成功', $param);
        }

        //得到配置
        //var_dump(bw_config('site_upload2_url',123));die;
        $tab_id = $this->request->get('tab_id');
        //查询所有分类
        $tab = [];
        //var_dump($tab);die;
        return view('editconfig', ['entity' => null, 'tab' => $tab, 'tab_id' => $tab_id]);
    }

    public function editconfig()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            unset($param['radio_value']);
            unset($param['checkbox_value']);
            unset($param['select_value']);
            if (in_array($param['config_name'], ['sort', 'status'])) return $this->error('字段[sort],[status]属于组合数据字段，请换个字段名');
            //var_dump($param);die;
            return $this->success('操作成功', $param);
        }
        $data = $this->request->get('data');
        if ($data) {
//            var_dump($data);die;
            $data = json_decode(str_replace("\\\\", "\\", htmlspecialchars_decode($data)), true);

            //如果是富文本则解析富文本数据
            if ($data['type'] == "r_textarea") {
                $r_textarea = base64_decode($data['value']);
                $data['value'] = urldecode($r_textarea);
            }
            unset($data['radio_value']);
            unset($data['checkbox_value']);
            unset($data['select_value']);
            $data['value'] = str_replace("__JING_HAO__","#",$data['value']);
            //var_dump($data);die;
        } else {
            $data = [];
        }
        $tab_id = $this->request->get('tab_id');

        // var_dump($data['parameter']);die;
        //查询所有分类
        $tab = [];

        return view('editconfig', ['entity' => $data, 'tab' => $tab, 'tab_id' => $tab_id]);
    }


    /**
     * 删除/批量删除
     *
     * @return \think\Response
     */
    public function configsoftdleting()
    {

        //门店ids
        $ids = input('ids/s');
        $ids_array = explode(',', $ids);
        $list = array();
        foreach ($ids_array as $key) {
            //如果存在子配置则不允许删除
//            if(ConfigTab::haveConfig($key)){
//                return 'paramFail';
//            }


            ConfigGroup::destroy($key);
        }

        //Offline::destroy($ids_array);
        return 'success';
    }


}